import React, { useState } from 'react';
import {
  Container,
  Typography,
  Box,
  Paper,
  Grid,
  TextField,
  Button,
  Select,
  MenuItem,
  FormControl,
  InputLabel,
  Card,
  CardContent,
  Stepper,
  Step,
  StepLabel,
  Alert,
  CircularProgress
} from '@mui/material';
import { useNavigate } from 'react-router-dom';

function Calculator() {
  const navigate = useNavigate();
  const [activeStep, setActiveStep] = useState(0);
  const [loading, setLoading] = useState(false);
  const [formData, setFormData] = useState({
    transportation: '',
    distance: '',
    electricity: '',
    meatConsumption: '',
    wasteProduction: ''
  });

  const [result, setResult] = useState(null);

  const steps = [
    '交通出行',
    '能源使用',
    '饮食习惯',
    '废物处理'
  ];

  const handleChange = (event) => {
    setFormData({
      ...formData,
      [event.target.name]: event.target.value
    });
  };

  const calculateFootprint = async () => {
    setLoading(true);
    try {
      // 模拟API调用
      await new Promise(resolve => setTimeout(resolve, 1000));
      
      const transportationEmissions = {
        car: 0.2,
        bus: 0.08,
        bike: 0,
        walk: 0
      };

      const carbonFootprint = (
        transportationEmissions[formData.transportation] * Number(formData.distance) +
        Number(formData.electricity) * 0.5 +
        Number(formData.meatConsumption) * 2.5 +
        Number(formData.wasteProduction) * 0.7
      ).toFixed(2);

      setResult(carbonFootprint);
    } catch (error) {
      console.error('计算失败:', error);
    } finally {
      setLoading(false);
    }
  };

  const handleNext = () => {
    if (activeStep === steps.length - 1) {
      calculateFootprint();
    } else {
      setActiveStep((prev) => prev + 1);
    }
  };

  const handleBack = () => {
    setActiveStep((prev) => prev - 1);
  };

  const getStepContent = (step) => {
    switch (step) {
      case 0:
        return (
          <Grid container spacing={3}>
            <Grid item xs={12}>
              <FormControl fullWidth>
                <InputLabel>主要交通方式</InputLabel>
                <Select
                  name="transportation"
                  value={formData.transportation}
                  onChange={handleChange}
                >
                  <MenuItem value="car">私家车</MenuItem>
                  <MenuItem value="bus">公共交通</MenuItem>
                  <MenuItem value="bike">自行车</MenuItem>
                  <MenuItem value="walk">步行</MenuItem>
                </Select>
              </FormControl>
            </Grid>
            <Grid item xs={12}>
              <TextField
                fullWidth
                label="每日通勤距离（公里）"
                name="distance"
                type="number"
                value={formData.distance}
                onChange={handleChange}
              />
            </Grid>
          </Grid>
        );
      case 1:
        return (
          <TextField
            fullWidth
            label="每月用电量（度）"
            name="electricity"
            type="number"
            value={formData.electricity}
            onChange={handleChange}
          />
        );
      case 2:
        return (
          <TextField
            fullWidth
            label="每周肉类消费（千克）"
            name="meatConsumption"
            type="number"
            value={formData.meatConsumption}
            onChange={handleChange}
          />
        );
      case 3:
        return (
          <TextField
            fullWidth
            label="每周产生垃圾量（千克）"
            name="wasteProduction"
            type="number"
            value={formData.wasteProduction}
            onChange={handleChange}
          />
        );
      default:
        return '未知步骤';
    }
  };

  return (
    <Container maxWidth="md">
      <Box sx={{ my: 4 }}>
        <Typography variant="h4" gutterBottom align="center">
          碳足迹计算器
        </Typography>
        <Typography variant="body1" paragraph align="center" color="text.secondary">
          通过回答以下问题，了解您的日常生活对环境的影响
        </Typography>

        <Paper sx={{ p: 3, mt: 3 }}>
          <Stepper activeStep={activeStep} sx={{ mb: 4 }}>
            {steps.map((label) => (
              <Step key={label}>
                <StepLabel>{label}</StepLabel>
              </Step>
            ))}
          </Stepper>

          {loading ? (
            <Box sx={{ display: 'flex', justifyContent: 'center', my: 4 }}>
              <CircularProgress />
            </Box>
          ) : result ? (
            <Box>
              <Alert severity="success" sx={{ mb: 3 }}>
                计算完成！
              </Alert>
              <Card>
                <CardContent>
                  <Typography variant="h5" gutterBottom align="center">
                    您的碳足迹计算结果
                  </Typography>
                  <Typography variant="h3" align="center" color="primary" sx={{ my: 3 }}>
                    {result} kg CO₂
                  </Typography>
                  <Typography variant="body1" paragraph>
                    根据您的生活习惯，您每周产生约 {result} 千克的二氧化碳排放。
                  </Typography>
                  <Box sx={{ mt: 3 }}>
                    <Typography variant="h6" gutterBottom>
                      减少碳足迹的建议：
                    </Typography>
                    <ul>
                      <li>尽量选择公共交通或绿色出行方式</li>
                      <li>减少肉类消费，增加蔬果摄入</li>
                      <li>注意节约用电，使用节能电器</li>
                      <li>实践垃圾分类，减少废物产生</li>
                    </ul>
                  </Box>
                  <Box sx={{ mt: 4, textAlign: 'center' }}>
                    <Button
                      variant="contained"
                      onClick={() => navigate('/challenges')}
                      sx={{ mr: 2 }}
                    >
                      参与环保挑战
                    </Button>
                    <Button
                      variant="outlined"
                      onClick={() => {
                        setResult(null);
                        setActiveStep(0);
                        setFormData({
                          transportation: '',
                          distance: '',
                          electricity: '',
                          meatConsumption: '',
                          wasteProduction: ''
                        });
                      }}
                    >
                      重新计算
                    </Button>
                  </Box>
                </CardContent>
              </Card>
            </Box>
          ) : (
            <Box>
              <Box sx={{ mb: 4 }}>
                {getStepContent(activeStep)}
              </Box>
              <Box sx={{ display: 'flex', justifyContent: 'space-between' }}>
                <Button
                  disabled={activeStep === 0}
                  onClick={handleBack}
                >
                  上一步
                </Button>
                <Button
                  variant="contained"
                  onClick={handleNext}
                >
                  {activeStep === steps.length - 1 ? '计算' : '下一步'}
                </Button>
              </Box>
            </Box>
          )}
        </Paper>
      </Box>
    </Container>
  );
}

export default Calculator; 